package com.group4.Servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.group4.DAO.ChannelDAO;
import com.group4.DAO.UserDAO;
import com.group4.DB.Channel;
import com.group4.DB.User;

@WebServlet(name = "AddChannel", displayName = "AddChannel", urlPatterns = { "/addChannel" })
public class AddChannel extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1430730240389816082L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/json");
		// Get the printwriter object from response to write the required json
		// object to the output stream

		String userName = request.getParameter("userName");
		String channelName = request.getParameter("channelName");

		PrintWriter out = response.getWriter();
		JsonObject jsonObject = new JsonObject();

		if (channelName == null || userName == null) {
			jsonObject.addProperty("error", "missing parameter!");
			out.print(jsonObject);
			out.flush();
		} else {
			UserDAO user = User.getUserWithUsername(userName);
			if (user != null) {
				ChannelDAO channel = new ChannelDAO();
				channel.setChannelName(channelName);
				channel.setOwnerId(user.getID());
				boolean res = Channel.addChannel(channel);
				if (res) {
					Gson gson = new Gson();
					String json = gson.toJson(channel);
					out.print(json);
					out.flush();
				} else {
					jsonObject.addProperty("error",
							"Error occured while adding channel!");
					out.print(jsonObject);
					out.flush();
				}

			} else {
				jsonObject.addProperty("error", "No such user");
				out.print(jsonObject);
				out.flush();
			}
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}
}
